<template>
	<div class="body-framework">
		<Header cNum="1" />
		<main>
			<div class="sidebar">
				<!-- 左侧下拉框 -->
				<el-select v-model="selectValue" placeholder="请选择组件" size="large">
					<el-option
						v-for="item in components"
						:key="item.value"
						:label="item.label"
						:value="item.value"
					/>
				</el-select>

				<!-- 卡片列表 -->
				<div class="card-list">
					<el-card
						v-for="card in filteredCards"
						:key="card.id"
						:class="{ isSelect: card.id === adetail[selectValue] }"
					>
						<div class="card-img" @click="toSelect(card)">
							<img :src="card.imagePath" alt="组件图片" />
							<p>{{ selectValue }}</p>
						</div>
						<div class="card-content">
							<p>名称：{{ card.name.value }}</p>
							<p v-for="(obj, prop) in getCardContent(card)" :key="prop">
								{{ obj.key }}：{{ obj.value }}
							</p>
						</div>
					</el-card>
				</div>
			</div>

			<!-- 右侧架构图 -->
			<div class="diagram">
				<div class="img-div">
					<img class="bj" src="@/assets/images/jg1.png" alt="" />
					<img class="cpu-img" :src="aimg['cpu']" alt="" />
					<img class="flash-img" :src="aimg['flash']" alt="" />
					<img class="memory-img" :src="aimg['memory']" alt="" />
					<img class="acc-img" :src="aimg['acc']" alt="" />
				</div>
				<div class="btn">
					<el-button type="primary" @click="openSave">保存</el-button>
				</div>
			</div>

			<el-dialog v-model="isSave" width="500" title="保存" align-center>
				<div class="dialog-main">
					<p>命名：</p>
					<el-input v-model="a_name" clearable />
				</div>
				<template #footer>
					<div class="dialog-footer">
						<el-button @click="isSave = false">取消</el-button>
						<el-button type="primary" @click="toSave"> 确定 </el-button>
					</div>
				</template>
			</el-dialog>
		</main>
		<Footer />
	</div>
</template>

<script setup>
	import Header from '@/components/Header/index.vue'
	import Footer from '@/components/Footer/index.vue'
	import { ref, computed, reactive, onMounted } from 'vue'
	import { useRouter } from 'vue-router'
	import { userStore } from '@/store/user'
	import { ElMessage } from 'element-plus'
	import { accList, flashList, memoryList, cpuList, saveFramework } from '@/api/framework'

	const router = useRouter()
	const user = userStore()

	const selectValue = ref('')

	const isSave = ref(false)
	const a_name = ref('')

	// const architect = {
	// 	id: 1,
	// 	name: '架构模版1',
	// 	cpu: {
	// 		value: 'cpu',
	// 		label: 'CPU（中央处理器）'
	// 	},
	// 	memory: {
	// 		value: 'memory',
	// 		label: 'SD_Memory（内存卡）'
	// 	},
	// 	flash: {
	// 		value: 'flash',
	// 		label: 'AHB_PFlash（闪存）'
	// 	},
	// 	acc: {
	// 		value: 'acc',
	// 		label: 'AHB_Accelerator（加速器）'
	// 	}
	// }

	// 下拉框选项
	// const componentKeys = Object.keys(architect)
	// 	.filter((key) => {
	// 		return typeof architect[key] === 'object' && architect[key] !== null
	// 	})
	// 	.map((key) => architect[key].value)

	// const components = componentKeys.flatMap((key) => {
	// 	const { value, label } = architect[key]
	// 	return { value, label }
	// })

	const componentKeys = ['cpu', 'memory', 'flash', 'acc']

	// 下拉框选项
	const components = [
		{ value: 'cpu', label: 'CPU（中央处理器）' },
		{ value: 'memory', label: 'SD_Memory（内存卡）' },
		{ value: 'flash', label: 'AHB_PFlash（闪存）' },
		{ value: 'acc', label: 'AHB_Accelerator（加速器）' }
	]

	const accCards = ref([])
	const flashCards = ref([])
	const cpuCards = ref([])
	const memoryCards = ref([])

	// 定义获取数据的函数
	const fetchData = async () => {
		accCards.value = (await accList()).data
		flashCards.value = (await flashList()).data
		cpuCards.value = (await cpuList()).data
		memoryCards.value = (await memoryList()).data
	}

	// 在组件挂载完成后调用获取数据函数
	onMounted(() => {
		fetchData()
	})

	// 根据选择过滤卡片
	const filteredCards = computed(() => {
		switch (selectValue.value) {
			case 'cpu':
				return cpuCards.value
			case 'memory':
				return memoryCards.value
			case 'flash':
				return flashCards.value
			case 'acc':
				return accCards.value
			default:
				return []
		}
	})

	const getCardContent = (card) => {
		const content = {}
		const regexToExclude = /^(id|name|imagePath)$/i
		for (const [key, value] of Object.entries(card)) {
			if (!regexToExclude.test(key)) {
				content[key] = value
			}
		}
		return content
	}

	const adetail = ref(
		componentKeys.reduce((acc, item) => {
			acc[item] = 0
			return acc
		}, {})
	)

	const aimg = ref(
		componentKeys.reduce((acc, item) => {
			acc[item] = ''
			return acc
		}, {})
	)

	const toSelect = (card) => {
		adetail.value[selectValue.value] = card.id
		aimg.value[selectValue.value] = card.imagePath
	}

	const openSave = () => {
		for (const key in adetail.value) {
			if (adetail.value[key] === 0) {
				ElMessage.error('组件未选择完整')
				return
			}
		}
		isSave.value = true
	}

	const toSave = async () => {
		if (a_name.value !== '') {
			const data = {
				architectName: a_name.value,
				flashId: adetail.value['flash'],
				cpuId: adetail.value['cpu'],
				memoryId: adetail.value['memory'],
				accId: adetail.value['acc'],
				userId: user.id
			}
			const rData = (await saveFramework(data)).data
			if (rData.code == 200) {
				ElMessage.success('架构保存成功')
				isSave.value = false
				router.replace('/analysis')
			} else {
				ElMessage.success(rData.msg)
			}
		} else {
			ElMessage.error('请填写架构名称')
		}
	}
</script>

<style lang="scss" scoped>
	.body-framework {
		width: 100vw;
		height: 100vh;
	}

	main {
		height: calc(100% - 225px);
		display: flex;
		padding: 25px 40px;
	}

	.sidebar {
		width: 450px;
		margin-right: 30px;
		padding: 0 10px;
	}

	.card-list {
		margin-top: 10px;
		border: 1px solid #dcdfe6;
		height: 85%;
		overflow: auto;
		padding: 5px 10px;
	}

	.isSelect {
		background: rgb(169, 255, 249);
	}

	:deep(.el-card) {
		height: 180px;
		margin-bottom: 10px;
		.el-card__body {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
		}
	}

	.card-img {
		width: 120px;
		margin-right: 20px;
		border: 1px solid grey;
		border-radius: 5px;
		display: flex;
		flex-direction: column;
		align-items: center;
		cursor: pointer;
		&:hover {
			box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.3);
		}
		img {
			width: 100px;
			margin: 5px 0;
		}
		p {
			width: 100%;
			height: 25px;
			line-height: 25px;
			text-align: center;
			font-size: 16px;
			background: red;
		}
	}

	.card-content {
		padding: 10px 0;
		flex: 1;
		p {
			font-size: 14px;
			height: 20px;
			line-height: 20px;
		}
	}

	.diagram {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		.img-div {
			height: 80%;
			position: relative;
			.bj {
				height: 100%;
			}
			img[src=''] {
				display: none;
			}
			.cpu-img {
				height: 80px;
				position: absolute;
				left: 14%;
				top: 24%;
			}
			.flash-img {
				height: 80px;
				position: absolute;
				left: 20%;
				bottom: 12%;
			}
			.memory-img {
				height: 80px;
				position: absolute;
				right: 21%;
				top: 23%;
			}
			.acc-img {
				height: 80px;
				position: absolute;
				right: 14%;
				bottom: 12%;
			}
		}
		.btn {
			width: 100%;
			margin-top: 20px;
			margin-right: 100px;
			text-align: end;
			.el-button {
				width: 120px;
				height: 40px;
				font-size: 18px;
			}
		}
	}

	.dialog-main {
		display: flex;
		align-items: center;
		justify-content: center;
		p {
			font-size: 18px;
		}
		.el-input {
			width: 60%;
			font-size: 18px;
		}
	}
</style>